<template>
  <div class="home">
    <header>
      <input type="text" v-model="inputVal" @keydown.enter="search">
    </header>
    <table border>
      <thead>
        <th>编号<sort :showPrice="issortId" @sort="sortId"></sort>
        </th>
        <th>名称</th>
        <th>价格<sort :showPrice="!issortId" @sort="sortPrice"></sort>
        </th>
      </thead>
      <tbody>
        <!-- slice  -->
        <!--1，0,3 -->
        <!--2，3,6 -->
        <!--3，6,9 -->

        <tr v-for="(item, index) in showList.slice((currentPage - 1) * pageSize, currentPage * pageSize)" :key="index">
          <td>{{ item.id }}</td>
          <td>{{ item.goods_name }}</td>
          <td>{{ item.price }}</td>
        </tr>
      </tbody>
    </table>
    <pagination :total="showList.length" :pageSize="pageSize" @cutPage="cutPage" @cutSize="cutSize"></pagination>
  </div>
</template>

<script>
// @ is an alias to /src
import axios from 'axios';
import sort from '../components/sort.vue'
import pagination from '../components/pagination.vue'
export default {
  name: 'HomeView',
  components: {
    sort,
    pagination
  },
  data() {
    return {
      allList: [], // 所有的数据
      showList: [], // 展示的数据
      inputVal: '', // 搜索的值
      issortId: true,
      pageSize: 3, // 每页显示的条数
      currentPage: 1, // 当前页码
    }
  },
  created() {
    axios.get('data.json').then(res => {
      this.allList = res.data.data;
      this.showList = res.data.data;
    })
  },
  methods: {
    search() { // 搜索事件
      // console.log(this.inputVal);
      this.showList = this.allList.filter(item => item.goods_name.includes(this.inputVal))
    },
    sortId(val) {
      // console.log(val);
      // this.showList
      this.issortId = true;
      // if (val) {
      //   this.showList.sort((a, b) => b.id - a.id);
      // } else {
      //   this.showList.sort((a, b) => a.id - b.id);
      // }

      this.showList.sort((a, b) => val ? (b.id - a.id) : (a.id - b.id));
    },
    sortPrice(val) { // 价格排序
      this.issortId = false;
      if (val) {
        this.showList.sort((a, b) => b.price - a.price);
      } else {
        this.showList.sort((a, b) => a.price - b.price);
      }
    },
    cutPage(val) { // 分页该表触发的函数
      this.currentPage = val;
      // console.log(this.currentPage);
    },
    cutSize(e) { // 每页显示多少条触发的函数
      // console.log(e.target.value);
      this.pageSize = e.target.value * 1;
    }
  }
}
</script>
<style lang="scss" scoped>
header {
  margin-bottom: 10px;
}

table {
  width: 100%;
}
</style>
